/**
 * 
 */
package models;

import java.util.ArrayList;
import java.util.Calendar;

import views.JProgressPanel;

import controllers.ProgressChangeEventListener;

/**
 * @author LAP
 *
 */
public class JProgressPanelDefaultModel implements JProgressPanelModel{
	
	private UpdateProgressTimer timerToGenerations;
	
	private ArrayList<ProgressChangeEventListener> listners;
	
	private JProgressPanel panelToUpdate;
	
	private UpdateDataGenerator generator;
	
	/**
	 * 
	 * @param finalDate
	 */
	public JProgressPanelDefaultModel(Calendar finalDate, JProgressPanel panelToUpdate) {
		if (finalDate == null) throw new NullPointerException("Final date must be not null");
		if (panelToUpdate == null) throw new NullPointerException("Panel must be not null");
		this.panelToUpdate = panelToUpdate;
		generator = new UpdateDataGenerator(finalDate);
		timerToGenerations = new UpdateProgressTimer(1000, this);
		listners = new ArrayList<ProgressChangeEventListener>();
	}
	
	public void start() {
		timerToGenerations.start();
	}
	
	public void stop() {
		timerToGenerations.stop();
	}
	
	public void setDelay(int delay) {
		timerToGenerations.setDelay(delay);
	}
	
	public int getDelay() {
		return timerToGenerations.getDelay();
	}
	
	public void setRepeats(boolean flag) {
		timerToGenerations.setRepeats(flag);
	}
	
	public boolean isRepeats() {
		return timerToGenerations.isRepeats();
	}
	
	public boolean isRunning() {
		return timerToGenerations.isRunning();
	}
	
	@Override
	public void addProgressChangeEventListner(ProgressChangeEventListener listner) {
		listners.add(listner);
	}
	@Override
	public void removeProgressChangeEventListner(ProgressChangeEventListener listner) {
		listners.remove(listner);
	}
	@Override
	public ProgressChangeEventListener[] getProgressChangeEventListners() {
		return listners.toArray(new ProgressChangeEventListener[listners.size()]);
	}
	
	private void fireProcessChangeEvent(ProgressChangeEvent event) {
		if (event == null) throw new NullPointerException("Event must be not null");
		for(ProgressChangeEventListener listner: listners) 
			listner.ProgressChange(event);
	}
	
	@Override
	public void updateProgressPanel() {
		Calendar calendar = Calendar.getInstance();
		try {
			generator.generate(calendar);
			panelToUpdate.setMaximum(generator.getZoomMaximum());
			panelToUpdate.setValue(generator.getPosition());
			fireProcessChangeEvent(new ProgressChangeEvent(
					panelToUpdate, 
					generator.getZoomMaximum(), 
					generator.getPosition()));
			panelToUpdate.setProgressString();
		} catch (UpdateProgressException e) {
			stop();
		}
	}
}
